import { showToast } from './toast'
import { getWechatProOpenIdIdByCode } from '../api/index'
import { getTokenValue, removeTokenValue, getUserInfo, removeUserInfo } from './storage'
// export let webUrl = 'https://bpai-h5-test.biaopu.cloud' // 测试环境
// export let webUrl = 'https://bpai-h5-pre.biaopu.cloud' // 预发布环境
export let webUrl = 'https://bpai-h5.biaopu.cloud' // 生产环境
// export let webUrl = 'http://172.16.0.73:52005' // 测试接口
export let baseUrl = webUrl + '/api/eimsWebApi' // 测试接口域名
/**
 * 封装请求
 */
export function request(options) {
  return new Promise((resolve, reject) => {
    let tokenValue = getTokenValue() || ''
    if (options.data && options.data.token) {
      tokenValue = options.data.token
      delete options.data.token
    }
    let header = {
      'content-type': 'application/json',
      'Client-Type': 'wechatPro',
      Authorization: tokenValue,
    }
    wx.request({
      url: baseUrl + options.url,
      data: options.data,
      timeout: 600000,
      header,
      method: options.method || 'POST',
      success: function (res) {
        let data = res.data
        if (data.code == '200') {
          resolve(data.result)
        } else if (data.code == '401') {
          showToast('登陆失效，请重新登录')
          removeTokenValue()
          removeUserInfo()
          setTimeout((() => {
            wx.reLaunch({
              url: '/pages/guide/guide',
            })
          }))
          reject(data)
        } else {
          showToast(data.message || '数据异常')
          reject(data)
        }
      },
      fail: function (err) {
        let { message } = error
        if (message === 'Network Error') {
          message = '本地网络异常，请检查网络后重试'
        } else if (message.includes('timeout')) {
          message = '系统接口请求超时'
        } else if (message.includes('Request failed with status code')) {
          message = '系统接口' + message.substr(message.length - 3) + '异常'
        } else {
          message = '网络请求异常'
        }
        showToast(message)
        reject(err)
      },
    })
  })
}


let wechat_openid = ''
async function getOpenid() {
  return new Promise((resolve) => {
    wx.login({
      success: async (res) => {
        let code = res.code
        try {
          let result = await getWechatProOpenIdIdByCode({ code })
          wechat_openid = result.openid || ''
          resolve('')
        } catch (error) {
        }
      },
    })
  })

}

export async function adRequest(options = {}) {
  if (!wechat_openid) {
    await getOpenid()
  }
  return new Promise((resolve) => {
    let header = {
      'content-type': 'application/json',
      'cache-control': 'no-cache'
    }
    let reqData = {
      "actions": [
        {
          "outer_action_id": "",// 选填，若上报可能有重复请填写该id，系统会根据该ID进行去重，详见FAQ
          "action_time": Math.round(new Date().getTime() / 1000).toString(),
          "user_id": {//user_id，可采集到的设备标示
            "wechat_openid": wechat_openid,//当为小程序类、公众号和企业微信转化时，此字段与wechat_unionid必传其一
            "wechat_unionid": "",//当为小程序类、公众号和企业微信转化时，此字段与wechat_openid必传其一
            "wechat_app_id": "wx6ff932dc70c95f0b",//用户发生该行为对应的小程序appid，该字段必填，并确保该appid已对该账户进行了授权（请参考帮助中心-转化归因使用指南-微信小程序转化归因操作手册中的appid授权部分）
          },
          "action_type": options.actionType, // 必填 行为类型
          "trace": {
            "click_id": options.gdtVid || "abc" // 必填 click_id
          }
        }
      ]
    }
    wx.request({
      url: 'https://tracking.e.qq.com/conv',
      data: JSON.stringify(reqData),
      timeout: 600000,
      header,
      method: 'POST',
      success: function (res) {
        console.info('adRes')
        console.info(res)
        resolve()
      },
      fail: function (err) {
        resolve()
      },
    })
  })
}
